from selenium.webdriver.common.by import By
from pages.base_page import Page


class PreChatPage(Page):
    ele_title = (By.ID, u'page-preChat-title')
    ele_error = (By.XPATH, u'//div[@role="alert"]')

    ele_feature_switch = (By.XPATH, u"//span[@data-tag='featureSwitch']")
    ele_use_prechat_form = (By.XPATH, u"//button[@value='form']")
    ele_trigger_a_task_bot = (By.XPATH, u"//button[@value='taskbot']")
    ele_is_enable_feature_switch = (By.XPATH, u"//span[@data-tag='featureSwitch']/span/div")
    ele_prechat_save_button = (By.XPATH, u"//button[@data-tag='formButton']/span[text()='Save']")

    ele_prechat_required_fields = (By.XPATH, u'//input[@name="isRequired"]')

    def __init__(self, driver, url, site_id):
        Page.__init__(self, driver, url)
        self.site_id = site_id
        self.url = url

    # this method should be called first
    def is_enable_feature_switch(self):
        fs = self.find_element(*self.ele_is_enable_feature_switch)
        if fs.text == 'OFF':
            self.click(self.ele_feature_switch)
        else:
            pass

    def check_prechat_page_eles(self):
        self.find_element(*self.ele_title).is_enabled()
        self.find_element(*self.ele_feature_switch).is_enabled()
        self.find_element(*self.ele_use_prechat_form).is_enabled()
        self.find_element(*self.ele_trigger_a_task_bot).is_enabled()
        self.find_element(*self.ele_is_enable_feature_switch).is_enabled()

    def clear_all_required_fields(self):
        required_fields = self.find_elements(*self.ele_prechat_required_fields)
        for field in required_fields:
            if field.get_attribute('value') == "true":
                try:
                    field.click()
                except Exception as e:
                    print("这个元素不能点击或visible为false", e)
            else:
                pass

    def prechat_button_save(self):
        self.click(self.ele_use_prechat_form)
        self.click(self.ele_prechat_save_button)
